<template>
  <ContentWrap>
    <CardTitle title="Form 动态表单组件" />
    
    <div class="demo-section">
      <h3>基础使用</h3>
      <p>Form 是一个基于 schema 配置的动态表单组件，支持多种表单控件和布局方式。</p>
      <code class="code-block mt-10px">
        &lt;Form 
          :schema="schema" 
          :model="formModel"
          @register="register"
        /&gt;
      </code>
    </div>

    <CardTitle title="演示示例" />

    <!-- 基础表单示例 -->
    <div class="demo-section">
      <h4>1. 基础表单</h4>
      <p>包含常用的输入控件：输入框、选择器、开关等</p>
      <Form
        ref="basicFormRef"
        :schema="basicSchema"
        :model="basicModel"
        @register="registerBasic"
      />
      <div class="form-actions">
        <el-button type="primary" @click="handleBasicSubmit">提交</el-button>
        <el-button @click="handleBasicReset">重置</el-button>
        <el-button @click="handleSetBasicValues">设置值</el-button>
      </div>
      <div class="result-display">
        <p><strong>表单数据：</strong></p>
        <pre>{{ JSON.stringify(basicModel, null, 2) }}</pre>
      </div>
    </div>

    <!-- 栅格布局表单 -->
    <div class="demo-section">
      <h4>2. 栅格布局表单</h4>
      <p>使用栅格系统实现响应式布局</p>
      <Form
        ref="gridFormRef"
        :schema="gridSchema"
        :model="gridModel"
        :is-col="true"
        :gutter="20"
        @register="registerGrid"
      />
      <div class="form-actions">
        <el-button type="primary" @click="handleGridSubmit">提交</el-button>
        <el-button @click="handleGridReset">重置</el-button>
      </div>
      <div class="result-display">
        <p><strong>栅格表单数据：</strong></p>
        <pre>{{ JSON.stringify(gridModel, null, 2) }}</pre>
      </div>
    </div>

    <!-- 高级表单示例 -->
    <div class="demo-section">
      <h4>3. 高级表单控件</h4>
      <p>包含日期选择、文件上传、富文本编辑器等高级控件</p>
      <Form
        ref="advancedFormRef"
        :schema="advancedSchema"
        :model="advancedModel"
        label-width="120px"
        @register="registerAdvanced"
      />
      <div class="form-actions">
        <el-button type="primary" @click="handleAdvancedSubmit">提交</el-button>
        <el-button @click="handleAdvancedReset">重置</el-button>
      </div>
      <div class="result-display">
        <p><strong>高级表单数据：</strong></p>
        <pre>{{ JSON.stringify(advancedModel, null, 2) }}</pre>
      </div>
    </div>

    <!-- 表单验证示例 -->
    <div class="demo-section">
      <h4>4. 表单验证</h4>
      <p>演示表单验证功能，包含必填、格式验证等</p>
      <Form
        ref="validationFormRef"
        :schema="validationSchema"
        :model="validationModel"
        label-width="120px"
        @register="registerValidation"
      />
      <div class="form-actions">
        <el-button type="primary" @click="handleValidationSubmit">验证并提交</el-button>
        <el-button @click="handleValidationReset">重置</el-button>
        <el-button @click="handleClearValidation">清除验证</el-button>
      </div>
      <div class="result-display">
        <p><strong>验证表单数据：</strong></p>
        <pre>{{ JSON.stringify(validationModel, null, 2) }}</pre>
      </div>
    </div>

    <!-- 动态表单示例 -->
    <div class="demo-section">
      <h4>5. 动态表单操作</h4>
      <p>演示动态添加、删除、修改表单字段</p>
      <Form
        ref="dynamicFormRef"
        :schema="dynamicSchema"
        :model="dynamicModel"
        label-width="120px"
        @register="registerDynamic"
      />
      <div class="form-actions">
        <el-button type="primary" @click="handleDynamicSubmit">提交</el-button>
        <el-button @click="addDynamicField">添加字段</el-button>
        <el-button @click="removeDynamicField">删除字段</el-button>
        <el-button @click="modifyDynamicField">修改字段</el-button>
      </div>
      <div class="result-display">
        <p><strong>动态表单数据：</strong></p>
        <pre>{{ JSON.stringify(dynamicModel, null, 2) }}</pre>
      </div>
    </div>

    <CardTitle title="属性说明" />
    <table class="properties-table">
      <thead>
        <tr>
          <th>属性名</th>
          <th>类型</th>
          <th>默认值</th>
          <th>说明</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>schema</td>
          <td>FormSchema[]</td>
          <td>[]</td>
          <td>表单配置数组</td>
        </tr>
        <tr>
          <td>model</td>
          <td>Object</td>
          <td>{}</td>
          <td>表单数据对象</td>
        </tr>
        <tr>
          <td>isCol</td>
          <td>Boolean</td>
          <td>false</td>
          <td>是否使用栅格布局</td>
        </tr>
        <tr>
          <td>gutter</td>
          <td>Number</td>
          <td>20</td>
          <td>栅格间距</td>
        </tr>
        <tr>
          <td>labelWidth</td>
          <td>String | Number</td>
          <td>'auto'</td>
          <td>标签宽度</td>
        </tr>
        <tr>
          <td>autoSetPlaceholder</td>
          <td>Boolean</td>
          <td>true</td>
          <td>是否自动设置 placeholder</td>
        </tr>
      </tbody>
    </table>

    <CardTitle title="FormSchema 配置说明" />
    <table class="properties-table">
      <thead>
        <tr>
          <th>属性名</th>
          <th>类型</th>
          <th>说明</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>field</td>
          <td>String</td>
          <td>字段名，唯一标识</td>
        </tr>
        <tr>
          <td>label</td>
          <td>String</td>
          <td>字段标签</td>
        </tr>
        <tr>
          <td>component</td>
          <td>ComponentName</td>
          <td>使用的组件类型</td>
        </tr>
        <tr>
          <td>componentProps</td>
          <td>Object</td>
          <td>组件的 props</td>
        </tr>
        <tr>
          <td>value</td>
          <td>Any</td>
          <td>默认值</td>
        </tr>
        <tr>
          <td>colProps</td>
          <td>Object</td>
          <td>栅格列属性</td>
        </tr>
        <tr>
          <td>formItemProps</td>
          <td>Object</td>
          <td>FormItem 属性</td>
        </tr>
        <tr>
          <td>hidden</td>
          <td>Boolean</td>
          <td>是否隐藏字段</td>
        </tr>
      </tbody>
    </table>

    <CardTitle title="支持的组件类型" />
    <table class="properties-table">
      <thead>
        <tr>
          <th>组件类型</th>
          <th>说明</th>
          <th>Element Plus 对应组件</th>
        </tr>
      </thead>
      <tbody>
        <tr><td>Input</td><td>输入框</td><td>ElInput</td></tr>
        <tr><td>InputNumber</td><td>数字输入框</td><td>ElInputNumber</td></tr>
        <tr><td>InputPassword</td><td>密码输入框</td><td>自定义组件</td></tr>
        <tr><td>Autocomplete</td><td>自动完成</td><td>ElAutocomplete</td></tr>
        <tr><td>Select</td><td>选择器</td><td>ElSelect</td></tr>
        <tr><td>SelectV2</td><td>虚拟选择器</td><td>ElSelectV2</td></tr>
        <tr><td>TreeSelect</td><td>树选择器</td><td>ElTreeSelect</td></tr>
        <tr><td>Cascader</td><td>级联选择器</td><td>ElCascader</td></tr>
        <tr><td>Radio</td><td>单选框组</td><td>ElRadioGroup</td></tr>
        <tr><td>Checkbox</td><td>多选框组</td><td>ElCheckboxGroup</td></tr>
        <tr><td>Switch</td><td>开关</td><td>ElSwitch</td></tr>
        <tr><td>Slider</td><td>滑块</td><td>ElSlider</td></tr>
        <tr><td>DatePicker</td><td>日期选择器</td><td>ElDatePicker</td></tr>
        <tr><td>TimePicker</td><td>时间选择器</td><td>ElTimePicker</td></tr>
        <tr><td>TimeSelect</td><td>时间选择</td><td>ElTimeSelect</td></tr>
        <tr><td>Rate</td><td>评分</td><td>ElRate</td></tr>
        <tr><td>ColorPicker</td><td>颜色选择器</td><td>ElColorPicker</td></tr>
        <tr><td>Transfer</td><td>穿梭框</td><td>ElTransfer</td></tr>
        <tr><td>Editor</td><td>富文本编辑器</td><td>自定义组件</td></tr>
        <tr><td>UploadImg</td><td>图片上传</td><td>自定义组件</td></tr>
        <tr><td>UploadImgs</td><td>多图上传</td><td>自定义组件</td></tr>
        <tr><td>UploadFile</td><td>文件上传</td><td>自定义组件</td></tr>
        <tr><td>Divider</td><td>分割线</td><td>ElDivider</td></tr>
      </tbody>
    </table>

    <CardTitle title="方法说明" />
    <table class="properties-table">
      <thead>
        <tr>
          <th>方法名</th>
          <th>参数</th>
          <th>说明</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>setValues</td>
          <td>(data: Object)</td>
          <td>设置表单数据</td>
        </tr>
        <tr>
          <td>setProps</td>
          <td>(props: FormProps)</td>
          <td>设置表单属性</td>
        </tr>
        <tr>
          <td>addSchema</td>
          <td>(schema: FormSchema, index?: number)</td>
          <td>添加表单字段</td>
        </tr>
        <tr>
          <td>delSchema</td>
          <td>(field: string)</td>
          <td>删除表单字段</td>
        </tr>
        <tr>
          <td>setSchema</td>
          <td>(props: FormSetPropsType[])</td>
          <td>修改表单字段属性</td>
        </tr>
        <tr>
          <td>getElFormRef</td>
          <td>-</td>
          <td>获取 ElForm 实例</td>
        </tr>
      </tbody>
    </table>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, unref } from 'vue'
import { useForm } from '@/hooks/web/useForm'
import type { FormSchema } from '@/types/form'
import { ElMessage } from 'element-plus'

// 表单数据
const basicModel = ref({
  name: '',
  email: '',
  age: null,
  gender: '',
  isVip: false,
  description: ''
})

const gridModel = ref({
  firstName: '',
  lastName: '',
  phone: '',
  address: '',
  city: '',
  zipCode: ''
})

const advancedModel = ref({
  startDate: '',
  endDate: '',
  timeRange: [],
  score: 0,
  color: '#409eff',
  content: '',
  avatar: '',
  files: []
})

const validationModel = ref({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  website: ''
})

const dynamicModel = ref({
  basicInfo: '',
  dynamicField: ''
})

// 基础表单配置
const basicSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '姓名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入姓名'
    },
    value: ''
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    componentProps: {
      placeholder: '请输入邮箱地址'
    }
  },
  {
    field: 'age',
    label: '年龄',
    component: 'InputNumber',
    componentProps: {
      min: 0,
      max: 120,
      placeholder: '请输入年龄'
    }
  },
  {
    field: 'gender',
    label: '性别',
    component: 'Radio',
    componentProps: {
      options: [
        { label: '男', value: 'male' },
        { label: '女', value: 'female' }
      ]
    }
  },
  {
    field: 'isVip',
    label: 'VIP用户',
    component: 'Switch'
  },
  {
    field: 'description',
    label: '描述',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 3,
      placeholder: '请输入描述信息'
    }
  }
])

// 栅格表单配置
const gridSchema = reactive<FormSchema[]>([
  {
    field: 'firstName',
    label: '名',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入名'
    }
  },
  {
    field: 'lastName',
    label: '姓',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入姓'
    }
  },
  {
    field: 'phone',
    label: '电话',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入电话号码'
    }
  },
  {
    field: 'address',
    label: '地址',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入地址'
    }
  },
  {
    field: 'city',
    label: '城市',
    component: 'Select',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请选择城市',
      options: [
        { label: '北京', value: 'beijing' },
        { label: '上海', value: 'shanghai' },
        { label: '广州', value: 'guangzhou' },
        { label: '深圳', value: 'shenzhen' }
      ]
    }
  },
  {
    field: 'zipCode',
    label: '邮编',
    component: 'Input',
    colProps: { span: 12 },
    componentProps: {
      placeholder: '请输入邮编'
    }
  }
])

// 高级表单配置
const advancedSchema = reactive<FormSchema[]>([
  {
    field: 'startDate',
    label: '开始日期',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      placeholder: '请选择开始日期',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    field: 'endDate',
    label: '结束日期',
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      placeholder: '请选择结束日期时间',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'timeRange',
    label: '时间范围',
    component: 'TimePicker',
    componentProps: {
      isRange: true,
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      format: 'HH:mm:ss',
      valueFormat: 'HH:mm:ss'
    }
  },
  {
    field: 'score',
    label: '评分',
    component: 'Rate',
    componentProps: {
      max: 5,
      showText: true,
      texts: ['极差', '失望', '一般', '满意', '惊喜']
    }
  },
  {
    field: 'color',
    label: '主题色',
    component: 'ColorPicker',
    componentProps: {
      showAlpha: true
    }
  },
  {
    field: 'content',
    label: '富文本内容',
    component: 'Editor',
    componentProps: {
      height: 200,
      placeholder: '请输入内容'
    }
  }
])

// 验证表单配置
const validationSchema = reactive<FormSchema[]>([
  {
    field: 'username',
    label: '用户名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户名'
    },
    formItemProps: {
      required: true,
      rules: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ]
    }
  },
  {
    field: 'password',
    label: '密码',
    component: 'InputPassword',
    componentProps: {
      placeholder: '请输入密码',
      showPassword: true
    },
    formItemProps: {
      required: true,
      rules: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }
  },
  {
    field: 'confirmPassword',
    label: '确认密码',
    component: 'InputPassword',
    componentProps: {
      placeholder: '请确认密码',
      showPassword: true
    },
    formItemProps: {
      required: true,
      rules: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule: any, value: string, callback: Function) => {
            if (value !== validationModel.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
  },
  {
    field: 'email',
    label: '邮箱',
    component: 'Input',
    componentProps: {
      placeholder: '请输入邮箱地址'
    },
    formItemProps: {
      required: true,
      rules: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }
  },
  {
    field: 'phone',
    label: '手机号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入手机号'
    },
    formItemProps: {
      rules: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    }
  },
  {
    field: 'website',
    label: '个人网站',
    component: 'Input',
    componentProps: {
      placeholder: '请输入个人网站地址'
    },
    formItemProps: {
      rules: [
        { type: 'url', message: '请输入正确的网站地址', trigger: 'blur' }
      ]
    }
  }
])

// 动态表单配置
const dynamicSchema = reactive<FormSchema[]>([
  {
    field: 'basicInfo',
    label: '基础信息',
    component: 'Input',
    componentProps: {
      placeholder: '请输入基础信息'
    }
  }
])

// 表单注册
const { register: registerBasic, elFormRef: basicFormRef, methods: basicMethods } = useForm({
  model: basicModel
})

const { register: registerGrid, elFormRef: gridFormRef, methods: gridMethods } = useForm({
  model: gridModel
})

const { register: registerAdvanced, elFormRef: advancedFormRef, methods: advancedMethods } = useForm({
  model: advancedModel
})

const { register: registerValidation, elFormRef: validationFormRef, methods: validationMethods } = useForm({
  model: validationModel
})

const { register: registerDynamic, elFormRef: dynamicFormRef, methods: dynamicMethods } = useForm({
  model: dynamicModel
})

// 事件处理函数
const handleBasicSubmit = async () => {
  const { getFormData } = basicMethods
  const data = await getFormData()
  ElMessage.success('基础表单提交成功！')
  console.log('基础表单数据:', data)
  basicModel.value = data
}

const handleBasicReset = () => {
  unref(basicFormRef)?.resetFields()
  ElMessage.info('基础表单已重置')
}

const handleSetBasicValues = () => {
  const { setValues } = basicMethods
  setValues({
    name: '张三',
    email: 'zhangsan@example.com',
    age: 25,
    gender: 'male',
    isVip: true,
    description: '这是一个测试用户'
  })
  ElMessage.success('已设置基础表单默认值')
}

const handleGridSubmit = async () => {
  const { getFormData } = gridMethods
  const data = await getFormData()
  ElMessage.success('栅格表单提交成功！')
  console.log('栅格表单数据:', data)
  gridModel.value = data
}


const handleGridReset = () => {
  unref(gridFormRef)?.resetFields()
  ElMessage.info('栅格表单已重置')
}

const handleAdvancedSubmit = async () => {
  const { getFormData } = advancedMethods
  const data = await getFormData()
  ElMessage.success('高级表单提交成功！')
  console.log('高级表单数据:', data)
  advancedModel.value = data
}

const handleAdvancedReset = () => {
  unref(advancedFormRef)?.resetFields()
  ElMessage.info('高级表单已重置')
}

const handleValidationSubmit = async () => {
  await unref(validationFormRef)?.validate(async (isValid) => {
    if (isValid) {
      const { getFormData } = validationMethods
      const data = await getFormData()
      ElMessage.success('验证表单提交成功！')
      console.log('验证表单数据:', data)
    } else {
      ElMessage.error('表单验证失败，请检查输入')
    }
  })
}

const handleValidationReset = () => {
  unref(validationFormRef)?.resetFields()
  ElMessage.info('验证表单已重置')
}

const handleClearValidation = () => {
  unref(validationFormRef)?.clearValidate()
  ElMessage.info('已清除验证状态')
}

const handleDynamicSubmit = async () => {
  const { getFormData } = dynamicMethods
  const data = await getFormData()
  ElMessage.success('动态表单提交成功！')
  console.log('动态表单数据:', data)
}

// 动态表单操作
let fieldCounter = 1

const addDynamicField = () => {
  fieldCounter++
  dynamicSchema.push({
    field: `dynamicField${fieldCounter}`,
    label: `动态字段${fieldCounter}`,
    component: 'Input',
    componentProps: {
      placeholder: `请输入动态字段${fieldCounter}`
    }
  })
  dynamicModel[`dynamicField${fieldCounter}`] = ''
  ElMessage.success(`已添加动态字段${fieldCounter}`)
}

const removeDynamicField = () => {
  if (dynamicSchema.length > 1) {
    const lastField = dynamicSchema.pop()
    if (lastField) {
      delete dynamicModel[lastField.field]
      ElMessage.success(`已删除字段: ${lastField.label}`)
    }
  } else {
    ElMessage.warning('至少保留一个字段')
  }
}

const modifyDynamicField = () => {
  if (dynamicSchema.length > 1) {
    const lastField = dynamicSchema[dynamicSchema.length - 1]
    lastField.label = `修改后的${lastField.label}`
    lastField.componentProps!.placeholder = `修改后的占位符`
    ElMessage.success('已修改最后一个字段属性')
  }
}
</script>

<style scoped>
.demo-section {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.demo-section h4 {
  margin-bottom: 15px;
  color: #303133;
  font-weight: 600;
}

.demo-section p {
  margin-bottom: 15px;
  color: #606266;
  line-height: 1.5;
}

.code-block {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.form-actions {
  margin: 20px 0;
  padding: 15px;
  background: #fafbfc;
  border-radius: 4px;
  display: flex;
  gap: 10px;
}

.result-display {
  margin-top: 15px;
  padding: 15px;
  background: #f0f9ff;
  border: 1px solid #b3e5fc;
  border-radius: 4px;
}

.result-display pre {
  margin: 10px 0 0 0;
  font-size: 12px;
  color: #2563eb;
  max-height: 200px;
  overflow-y: auto;
}

.properties-table {
  width: 100%;
  border-collapse: collapse;
  margin: 15px 0;
}

.properties-table th,
.properties-table td {
  border: 1px solid #e4e7ed;
  padding: 12px;
  text-align: left;
}

.properties-table th {
  background: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

.properties-table td {
  color: #606266;
}

.properties-table code {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}
</style> 